package cn.client.data.remoteData.repository

import cn.client.data.remoteData.ApiService
import cn.client.data.remoteData.bean.BaseResp
import cn.client.data.remoteData.bean.DynamicData
import cn.client.data.remoteData.bean.PageSelectByUid
import cn.client.data.remoteData.bean.PublishDynamic
import cn.client.data.remoteData.bean.TakeD
import cn.client.data.remoteData.bean.UserInfoCards
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import javax.inject.Inject

class DynamicRepository @Inject constructor(private val apiService: ApiService) {

    /**
     * 上传动态
     */
    suspend fun publishDynamic(request: PublishDynamic): BaseResp<Any> {
        val uidBody = request.uid.intToRequestBody()
        val contentBody = request.content.strToRequestBody()
        val categoryBody = request.category.intToRequestBody()
        val imagesBody = convertList(request.images)
        val subjectBody = request.subject?.map { subjectPart ->
            subjectPart.intToRequestBody()
        }?.joinToString(",")?.strToRequestBody()
        return apiService.publishDynamic(
            uidBody,
            contentBody,
            categoryBody,
            imagesBody,
            subjectBody
        )
    }

    /**
     * 获取动态列表
     */
    suspend fun selectDynamicList(selectDynamicList: PageSelectByUid): BaseResp<List<DynamicData>> {
        return apiService.selectDynamicList(selectDynamicList)
    }


    suspend fun selectDynamic(selectDynamic: TakeD): BaseResp<DynamicData> {
        return apiService.selectDynamic(selectDynamic)
    }


    private fun Int.intToRequestBody(): RequestBody {
        return this.toString()
            .toRequestBody("text/plain".toMediaTypeOrNull())
    }

    // 私有辅助方法，将字符串转换为指定媒体类型的 RequestBody
    private fun String.strToRequestBody(): RequestBody {
        return this
            .toRequestBody("text/plain".toMediaTypeOrNull())
    }

    private fun createFilePart(file: File): MultipartBody.Part {
        val requestFile = file.asRequestBody("image/*".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData("images", file.name, requestFile)
    }


    // 将文件列表转换为MultipartBody.Part列表
    private fun createMultipartBodyParts(files: List<File>): List<MultipartBody.Part> {
        return files.mapIndexed { _, file ->
            val requestBody = file
                .asRequestBody("image/*".toMediaTypeOrNull())
            MultipartBody.Part.createFormData("images[]", file.name, requestBody)
        }
    }

    private fun convertList(fileList: List<File>): List<MultipartBody.Part> {
        return fileList.map { file ->
            MultipartBody.Part.createFormData("images", file.name,
                file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
            )
        }
    }

}